package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<ShopType> getList() {
        // 1. 查询缓存中ShopTypeList
        List<String> shopTypeStrList = stringRedisTemplate.opsForList().range(CacheConstant.SHOP_LIST_CACHE, 0, -1);
        // 2. 判断shopTypeList是否存在
        List<ShopType> shopTypeList = new ArrayList<>();
        if (shopTypeStrList != null){
            for (String shopTypeStr : shopTypeStrList) {
                if (!StrUtil.isBlank(shopTypeStr)) {
                    ShopType shopType = JSONUtil.toBean(shopTypeStr, ShopType.class);
                    shopTypeList.add(shopType);
                }
            }
            return shopTypeList;
        }
        // 3. 不存在, 则查询数据库
        shopTypeList = this.getList();
        // 4. 判断数据库中是否存在shopTypeList
        if (shopTypeList == null){
            return null;
        }
        // 5. 将查询出的shopTypeList存储到缓存中
        for (ShopType shopType : shopTypeList) {
            String shopTypeStr = JSONUtil.toJsonStr(shopType);
            if (!StrUtil.isBlank(shopTypeStr)){
                shopTypeStrList.add(shopTypeStr);
            }
        }
        stringRedisTemplate.opsForList().leftPushAll(CacheConstant.SHOP_LIST_CACHE,shopTypeStrList);
        return shopTypeList;
    }
}
